<?php namespace App\Services;

use App\User;
use Illuminate\Http\Request;
use Exception;

class UserService
{

    public function getList(Request $request)
    {
        $params = [];
        if ($request->input('role_id'))
            $params['role_id'] = $request->input('role_id');
        $search = User::where($params);
        if (($request->input('name')))
            $search->where('name', 'like', '%' . $request->input('name') . '%');
        return $search->orderBy($request->input('orderField', 'id'), $request->input('orderDirection', 'asc'))
            ->paginate($request->input('pageSize', config('view')['numPerPage']));
    }


    public function create(Array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'],
            'gender' => $data['gender'],
            'address' => $data['address'],
            'role_id' => $data['role_id'],
            'password' => bcrypt($data['password']),
        ]);
    }

    public function update($id, Array $data)
    {
        $user = User::find($id);
        if ($user->phone != $data['phone'] && User::withTrashed()->where('phone', $data['phone'])->count() > 0) {
            throw new Exception('此手机号码已被绑定');
        }
        $user->name = $data['name'];
        $user->phone = $data['phone'];
        $user->gender = $data['gender'];
        $user->address = $data['address'];
        $user->role_id = isset($data['role_id']) ? $data['role_id'] : $user->role_id;
        return $user->save();
    }

    public function delete($id)
    {
        return User::find($id)->delete();
    }

    public function changePassword($id, $password)
    {
        $user = User::find($id);
        $user->password = bcrypt($password);
        $user->save();
    }
}